package com.slz3.business.task;

import com.alibaba.fastjson.JSON;
import com.slz3.business.frame.WuLiu.WuliuMainVO;
import com.slz3.business.frame.enums.ValidFlag;
import com.slz3.business.frame.module.Repositorys;
import com.slz3.business.frame.module.Services;
import com.slz3.business.frame.redis.Jedis;
import com.slz3.business.frame.redis.RK;
import com.slz3.business.frame.steward.Steward;
import com.slz3.business.module.orderManagement.ordOrder.domain.OrdOrder;
import com.slz3.business.module.orderManagement.ordOrder.domain.Order;
import com.slz3.business.module.orderManagement.ordOrder.domain.OrderDetailGroup;
import com.slz3.business.module.orderManagement.ordOrder.enums.OrdOrderStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

import static java.util.stream.Collectors.toList;


/**
 * 系统自动确认收货的定时器，需要没半个小时进想执行一次
 * <p>
 * 执行的规则是：
 * 1 查询系统中所有已经发货当时未确认收货的订单。
 * 2 轮询查询这些订单的物流状态，如果是已经签收，这改变订单的状态为已经签收
 */

@Slf4j
@Component
public class AutoConfimOrdierTaskTimer {


    /**
     * @Description：优惠券同步 每天晚上1点执行
     * 0 3 * * * ?
     * 0 30 0 1/1 * ?
     */
    @Scheduled(cron = "0 3 * * * ?")
    private void sysncDrawTicket() {
        log.info("定时执行订单签收状态的系统自动签收开始");
        List<OrdOrder> ordOrderList = findAllNoConfirmReceiverOrder();
        for (OrdOrder ordOrder : ordOrderList) {
            if (getWuLiuInfo(ordOrder.getUuid().toString())) {
                confirmReceiver(ordOrder);
            }
        }
        log.info("定时执行订单签收状态的系统自动签收结束");
    }


    //判断该订单是否已经是已经签收了
    public Boolean getWuLiuInfo(String orderUUid) {
        try {
            Map<String, Object> wuliuinfoMap = Jedis.db0.getMap(RK.SERVICE__ORDER_LOGISTICS__ORDER_UUID__$UUID$.replace("${uuid}", orderUUid));
            log.info("订单：" + orderUUid + "，物流信息:" + wuliuinfoMap);
            if (wuliuinfoMap.get("logisticsCompanyPinyin") != null && wuliuinfoMap.get("logisticsNo") != null) {
                String wuliuSpellName = wuliuinfoMap.get("logisticsCompanyPinyin").toString();
                String wuliuNum = wuliuinfoMap.get("logisticsNo").toString();
                String wuliuInfoStr = getWuLiuInfo(wuliuSpellName, wuliuNum);
                log.info("物流详细信息：" + wuliuInfoStr);
                WuliuMainVO wuliuMainVO = JSON.parseObject(wuliuInfoStr, WuliuMainVO.class);
                if (wuliuMainVO != null && wuliuMainVO.getState() != null && wuliuMainVO.getState().equals("3")) {
                    return true;
                }
            }
        } catch (Exception ex) {
            log.error("查询物流信息异常：" + ex);
        }
        return false;

    }

    //http做post请求代码
    public static String getWuLiuInfo(String wuliuNameSpel, String wuliuNum) {
        String key = "NzCRPKGF1494";
        String customer = "6CB682FBED836715F852EE251D25EEED";
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("com", wuliuNameSpel);
        paramMap.put("num", wuliuNum);
        paramMap.put("from", "");
        paramMap.put("to", "");
        paramMap.put("resultv2", "1");
        String param = JSON.toJSONString(paramMap);
        String sign = org.apache.commons.codec.digest.DigestUtils.md5Hex(param + key + customer).toUpperCase();
        HttpPost post = new HttpPost("http://poll.kuaidi100.com/poll/query.do");
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("customer", customer));
        params.add(new BasicNameValuePair("sign", sign));
        params.add(new BasicNameValuePair("param", param));
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse resp = null;
        String lastResult = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(params));
            resp = client.execute(post);
            if (null != resp && null != resp.getEntity()) {
                lastResult = EntityUtils.toString(resp.getEntity());
                log.info("lastResult:" + lastResult);
                System.out.println(lastResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取物流信息异常：" + e);
        } finally {
            try {
                if (null != resp) {
                    resp.close();
                }
                if (null != client) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                log.error("网络异常：" + e);
            }
        }
        return lastResult;
    }


    /**
     * 进行订单的确认发货
     *
     * @param order
     */
    private void confirmReceiver(OrdOrder order) {
        order.setSerOrderStatus(OrdOrderStatusEnum.AL_RECEIVER.getCode());
        Services.ordOrder.modify(order);
        String orderInfoKey = RK.SERVICE__ORDER__INFO__ORDER_UUID__$UUID$.replace("${uuid}", order.getUuid().toString());
        Order order1 = Order.builder().build();
        Map<String, Object> orderMap = Jedis.db0.getMap(orderInfoKey);
        Steward.map2Obj(orderMap, order1);
        order1.setSerOrderStatus(order.getSerOrderStatus().toString());
        String orderWaitReceiverPageKey = String.format("%s:%s:%s:%s:%s", RK.SERVICE, RK.ORDER, RK.PAGING, RK.WAIT_RECIEVER, order.getUuid().toString());
        Jedis.db0.removeFromList(orderWaitReceiverPageKey, 0, order.getUuid().toString());
        Jedis.db0.set(orderInfoKey, Steward.obj2Map(order1));

        String orderDetailGroupUuidKeyList = RK.SERVICE__ORDER__JOIN__ORDER_DETAIL_GROUP__ORDER_UUID__$UUID$.replace("${uuid}",order1.getSerOrderUuid());
        Set<Object> orderDetailGroupUuidObjList = Jedis.db0.getSet(orderDetailGroupUuidKeyList);
        List<String> orderDetailGroupInfokeyList = orderDetailGroupUuidObjList.stream().filter(item->item!=null).map(item-> {
            String orderDetailGroupInfokey =  RK.SERVICE__ORDER_DETAIL_GROUP__INFO__ORDER_DETAIL_GROUP_UUID__$UUID$.replace("${uuid}", item.toString());
            return orderDetailGroupInfokey;
        }).collect(toList());

        List<Object> orderDetailGroupInfoObj = Jedis.db0.getListByKey(orderDetailGroupInfokeyList);
        List<OrderDetailGroup> orderDetailGroupList = orderDetailGroupInfoObj.stream().map(item -> {
            Map<String,Object> orderDetailGroupInfoMap = (Map) item;
            OrderDetailGroup orderDetailGroup = OrderDetailGroup.builder().build();
            Steward.map2Obj(orderDetailGroupInfoMap,orderDetailGroup);
            return orderDetailGroup;
        }).collect(toList());

        orderDetailGroupList.stream().filter(item->item!=null).forEach(orderDetailGroup -> {
            orderDetailGroup.setSerOrderStatus(order1.getSerOrderStatus());
            String orderDetailGroupInfoKey = RK.SERVICE__ORDER_DETAIL_GROUP__INFO__ORDER_DETAIL_GROUP_UUID__$UUID$.replace("${uuid}",orderDetailGroup.getUuid());
            String orderDetailSortWaitReceiverKey = RK.SERVICE__ORDER_DETAIL_GROUP__SORT__WAIT_RECEIVER__MEMBER_UUID__$UUID$.replace("${uuid}",orderDetailGroup.getSerMemberUuid());

            Jedis.db0.removeFromList(orderDetailSortWaitReceiverKey,0,orderDetailGroup.getUuid());
            Jedis.db0.set(orderDetailGroupInfoKey,Steward.obj2Map(orderDetailGroup));
        });
    }

    /**
     * 获取所有的已经发货但是还未确认收货的订单列表
     *
     * @return
     */
    private List<OrdOrder> findAllNoConfirmReceiverOrder() {
        List<OrdOrder> returnOrderList = new ArrayList<OrdOrder>();
        List<OrdOrder> ordOrderList = Repositorys.ordOrder.findAll();
        for (OrdOrder ordOrder : ordOrderList) {
            if (ordOrder.getValidFlag() != null && ordOrder.getSerOrderStatus() != null && ordOrder.getValidFlag().equals(ValidFlag.VALID) && ordOrder.getSerOrderStatus() == OrdOrderStatusEnum.WAIT_RECEIVER.getCode().intValue()) {
                returnOrderList.add(ordOrder);
            }
        }
        return returnOrderList;
    }


}
